using System;
using System.Web;
using System.Net;
using System.Xml;
using AUSRIS.Framework.Logging;
using AUSRIS.Reports.Extensions.Security.ReportService2005;

namespace AUSRIS.Reports.Extensions.Security.Authentication
{
	/// <summary>
	/// Extends the server proxy to support authentication ticket (cookie) management
	/// </summary>
	public class ReportServerProxy : ReportingService2005
	{
		#region Private Fields

		private Cookie authCookie = null;

		#endregion

		#region Private Properties

		private Cookie AuthCookie
		{
			get
			{
				if ( authCookie == null )
				{
					authCookie = CookieUtility.TranslateToCookie(HttpContext.Current.Request.Cookies[CookieUtility.CustomAuthCookieName]);
				}
				return authCookie;
			}
			set
			{
				authCookie = value;
			}
		}

		#endregion

		#region Overridden Methods

		protected override WebRequest GetWebRequest(Uri uri)
		{
#if DEBUG
			Log.Debug(Log.GetSource(), "uri: {0}", uri);
#endif
			HttpWebRequest httpWebRequest = (HttpWebRequest) HttpWebRequest.Create(uri);
			CookieContainer cookieContainer = new CookieContainer();
			httpWebRequest.CookieContainer = cookieContainer;
			Cookie authCookie = AuthCookie;
			//If the client already has an auth cookie, place it in the request's cookie container
			if ( authCookie != null )
			{
				httpWebRequest.CookieContainer.Add(authCookie);
			}
			httpWebRequest.Timeout = -1;
			httpWebRequest.Headers.Add("Accept-Language", HttpContext.Current.Request.Headers["Accept-Language"]);
			return httpWebRequest;
		}

		protected override WebResponse GetWebResponse(WebRequest request)
		{
#if DEBUG
			Log.Debug(Log.GetSource(), "uri: {0}", request.RequestUri);
#endif
			WebResponse webResponse = base.GetWebResponse(request);
			string cookieName = webResponse.Headers["RSAuthenticationHeader"];
			// If the response contains an auth header, store the cookie
			if ( cookieName != null )
			{
				CookieUtility.CustomAuthCookieName = cookieName;
				HttpWebResponse httpWebResponse = (HttpWebResponse) webResponse;
				Cookie authCookie = httpWebResponse.Cookies[cookieName];
				// If the auth cookie is null, throw an exception
				if ( authCookie == null )
				{
					throw new Exception("Authentication ticket not received by LogonUser");
				}
				AuthCookie = authCookie;
				CookieUtility.RelayCookieToClient(authCookie);
			}
			return webResponse;
		}

		#endregion
	}
}
